<template>
	<view class="page" v-if="pageData.template.files.length">
		<view class="order-content">
			<view class="info-box">
				<view class="label">{{ pageData.template.name }}</view>
				<view class="template" style="margin-bottom: 0;">
					<up-scroll-list :indicator="false" style="padding-bottom: 0;">
						<view v-for="(item, index) in images" :key="index">
							<image :src="item.url + '?style=imageMogr2/thumbnail/1200x'" mode="cover" style="width: 254rpx; height: 338rpx;"></image>
						</view>
						<video :src="pageData.template.movieUrl" class="video" object-fit="fill" :poster="pageData.template.movieThumbnailUrl+'?style=imageMogr2/thumbnail/1200x'"></video>
					</up-scroll-list>
				</view>
			</view>
			<view class="info-box" style="padding-bottom: 10rpx;">
				<view class="label" style="margin-bottom: 0;">使用形象</view>
				<view class="template">
					<view class="template-icon">
						<image :src="userAvatar" mode="aspectFit" style="width: 162rpx; height: 216rpx; border-radius: 16rpx;" />
					</view>
				</view>
				<view class="product-info">
					<view class="product-title">订单金额</view>
					<!-- 全图片 -->
					<view class="price" v-if="pageData.makeData.type == 0">¥ {{ pageData.template.price / 100 }}</view>
					<!-- 1图片1视频 -->
					<view class="price" v-if="pageData.makeData.type == 1">¥ {{ pageData.template.moviePrice / 100 }}</view>
				</view>
				<view class="coupon-section">
					<view class="coupon-text">优惠券</view>
					<view class="coupon-value" @click="selectCoupon">
						{{ couponName }}
						<view style="display: inline-flex;">
							<up-icon name="arrow-right" color="#999999" top="1.5"></up-icon>
						</view>
					</view>
				</view>
				<view class="coupon-section">
					<view class="coupon-text">体型</view>
					<view class="coupon-value" @click="selectTixing">
						{{ tixingName }}
						<view style="display: inline-flex;">
							<up-icon name="arrow-right" color="#999999" top="1.5"></up-icon>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bottom-bar">
			<view class="payment-amount">
				<text>待支付：</text>
				<text class="amount">¥ {{ totalPrice }}</text>
			</view>
			<button class="submit-btn" @click="handleSubmit">立即制作</button>
		</view>
		<!-- 优惠券 picker -->
		<up-picker v-model:show="pageData.showPicker" v-model="couponId" ref="couponPickerRef" title="我的优惠券" :columns="pageData.coupons"
			keyName="name" valueName="uuid" @confirm="handlePickerConfirm" cancelText="删除" @cancel="handlePickerCancel" confirmColor="#D19973"></up-picker>
		<!-- 体型 picker -->
		<up-picker v-model:show="pageData.showTixingPicker" v-model="tixingId" ref="tixingPickerRef" title="体型" :columns="[tixingData]"
			keyName="name" valueName="id" @confirm="handleTxPickerConfirm" cancelText="删除" @cancel="handleTxPickerCancel" confirmColor="#D19973"></up-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from 'vue';

	import {
		onLoad
	} from '@dcloudio/uni-app'

	const pageData = reactive({
		uuid: null,
		token: null,
		userImages: {
			fImg: {},
		},
		template: {
			files: []
		},
		coupons: [],
		showPicker: false,
		makeData: {}
	})
	const couponPickerRef = ref(null)
	const couponId = ref([])
	onLoad((option) => {
		pageData.makeData = uni.getStorageSync('makeData')
		pageData.uuid = option.uuid
		pageData.token = uni.getStorageSync('token')
		pageData.userImages = uni.getStorageSync('userImages') || {}
		getTemlateData()
		getMyCoupon()
	})

	const userAvatar = computed(() => {
		return pageData.userImages.fImg.url
	})
	const images = computed(() => {
		const list = pageData.template.files
		const makeData = uni.getStorageSync('makeData')
		if (makeData.type == 0) {
			return list
		} else {
			const arr = list.filter(file => file.uuid == makeData.iuuid)
			return arr
		}
	})
	const showTixingPicker = ref(false)
	const tixingId = ref([0])
	const tixingData = reactive([
		{
			url: `${getApp().globalData.imgUrl}/prod-api/files/down/1935907506884620288`,
			id: 0,
			name: '标准体型',
		},
		{
			url: `${getApp().globalData.imgUrl}/prod-api/files/down/1935907586509287424`,
			id: 1,
			name: '更加丰满'
		}
	])
	const merchant = uni.getStorageSync('merchant')
	const handleSubmit = () => {
		const params = {
			photoId: pageData.uuid,
			couponId: couponId.value[0] ? couponId.value[0] : null,
			frontUrl: pageData.userImages.fImg.url,
			shape: tixingId.value[0],
			type: pageData.makeData.type
		}
		if (pageData.makeData.type == 1) {
			params.fileId = pageData.makeData.iuuid
		}
		if (merchant) {
			params.merchant = merchant
		}
		// 处理提交逻辑
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/pay/wx`,
			method: 'POST',
			header: {
				'Authorization': "Bearer " + pageData.token,
			},
			data: params,
			success: (res) => {
				if (res.data.code === 200) {
					const { free, paySign, photoPay } = res.data
					if (free === '0') {
						// 微信支付
						const orderId = JSON.parse(res.data.pay.att).photoPayId
						const { timeStamp, nonceStr, signType, sign } = paySign
						wx.requestPayment({
							timeStamp,
							nonceStr,
							package: paySign.package,
							signType,
							paySign: sign,
							success(sres) {
								console.log('支付成功', sres)
								markingFn(orderId)
							},
							fail (sres) {
								console.log('支付失败', sres)
								uni.showToast({
									icon: 'error',
									title: '支付失败'
								})
							}
						})
					} else {
						// 免费不需要支付
						const orderId = photoPay.uuid
						markingFn(orderId)
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '系统开小差了'
					})
				}
			},
			fail: (error) => {
				uni.showToast({
					icon: 'none',
					title: '系统开小差了'
				})
			}
		});
	};
	
	function markingFn(orderId) {
		uni.showToast({
			title: '制作中',
			icon: 'loading',
			duration: 1500
		});
		setTimeout(() => {
			uni.showModal({
				content: '制作时间大约几分钟，5s后自动为您跳转订单详情',
				cancelText: '继续制作',
				confirmText: '订单详情',
				cancelColor: '#D19973',
				confirmColor: '#D19973',
				success: function (sres) {
					if (sres.confirm) {
						uni.navigateTo({
							url: `/pages/order/detail?uuid=${orderId}`
						})
					} else if (sres.cancel) {
						uni.navigateTo({
							url: '/pages/filter/filter?age=0&category=0'
						})
					}
				}
			})
		}, 1500)		
		setTimeout(() => {
			uni.navigateTo({
				url: `/pages/order/detail?uuid=${orderId}`
			})
		}, 5000)
	}
	
	// 获取套系详情
	function getTemlateData() {
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/photos/${pageData.uuid}`,
			method: 'GET',
			header: {
				'Authorization': "Bearer " + pageData.token,
			},
			success: (res) => {
				if (res.data.code === 200) {
					pageData.template = res.data.data
				} else {
					uni.showToast({
						icon: 'none',
						title: '系统开小差了'
					})
				}
			},
			fail: (error) => {
				uni.showToast({
					icon: 'none',
					title: '系统开小差了'
				})
			}
		});
	}

	// 获取我的未使用优惠券
	function getMyCoupon() {
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/coupons/my`,
			method: 'GET',
			header: {
				'Authorization': "Bearer " + pageData.token,
			},
			data: {
				status: 0,
				pageNum: 1,
				pageSize: 9999
			},
			success: (res) => {
				if (res.data.code === 200) {
					pageData.coupons = [res.data.rows]
				} else {
					uni.showToast({
						icon: 'none',
						title: '系统开小差了'
					})
				}
			},
			fail: (error) => {
				uni.showToast({
					icon: 'none',
					title: '系统开小差了'
				})
			}
		});
	}
	
	// 选择的优惠券名称
	const couponName = computed(() => {
		if (pageData.coupons.length) {
			const arr = pageData.coupons[0].filter(item => item.uuid === couponId.value[0])
			let name
			if (arr.length) {
				name = `${arr[0].name}`
			} else {
				name = '请选择'
			}
			return name
		} else {
			return '暂无可用'
		}
		
	})
	
	// 选择的体型名称
	const tixingName = computed(() => {
		const arr = tixingData.filter(item => item.id === tixingId.value[0])
		console.log(tixingData, tixingId.value[0], arr)
		let name
		if (arr.length) {
			name = arr[0].name
		} else {
			name = '请选择'
		}
		return name
		
	})
	
	// 计算实付价格
	const totalPrice = computed(() => {
		if (pageData.makeData.type == 1) {
			// 1图片+视频
			let total = pageData.template.moviePrice / 100
			if (pageData.coupons.length && couponId.value[0]) {
				const couponItem = pageData.coupons[0].filter(item => item.uuid === couponId.value[0])[0]
				const { type, subMoney } = couponItem
				if (type == 2) {
					// 折扣券 subMoney=8折
					total = pageData.template.moviePrice * subMoney / 100 / 10
				} else {
					// 金额券  subMoney=8元
					total = (pageData.template.moviePrice - subMoney *100) < 0 ? 0 : ((pageData.template.moviePrice - subMoney *100) /100)
				}
			}
			return total.toFixed(2)
		} else {
			// 全图片
			let total = pageData.template.price / 100
			if (pageData.coupons.length && couponId.value[0]) {
				const couponItem = pageData.coupons[0].filter(item => item.uuid === couponId.value[0])[0]
				const { type, subMoney } = couponItem
				if (type == 2) {
					// 折扣券 subMoney=8折
					total = pageData.template.price * subMoney / 100 / 10
				} else {
					// 金额券  subMoney=8元
					total = (pageData.template.price - subMoney *100) < 0 ? 0 : ((pageData.template.price - subMoney *100) /100)
				}
			}
			return total.toFixed(2)
		}
	})
	// 选择优惠券
	function selectCoupon() {
		if (pageData.coupons[0].length) {
			pageData.showPicker = true
		}
	}
	
	// 优惠券选择--确认
	function handlePickerConfirm(value) {
		couponId.value = [value.value[0].uuid]
	}
	
	// 删除优惠券
	function handlePickerCancel() {
		couponId.value = []
	}
	
	function selectTixing() {
		pageData.showTixingPicker = true
	}
	// 优惠券选择--确认
	function handleTxPickerConfirm(value) {
		tixingId.value = [value.value[0].id]
	}
	
	// 删除优惠券
	function handleTxPickerCancel() {
		tixingId.value = []
	}
</script>

<style lang="scss" scoped>
	.order-content {
		background-color: #ffffff;
		padding: 30rpx 40rpx 15rpx;
	}

	.label {
		font-family: PingFang SC;
		font-weight: 600;
		font-style: Heavy;
		font-size: 28rpx;
		leading-trim: NONE;
		line-height: 40rpx;
		letter-spacing: 0%;
		color: #333333;
		margin-bottom: 24rpx;
	}

	.info-box {
		background: #FEF8F6;
		padding: 24rpx;
		border-radius: 20rpx;
		margin-bottom: 24rpx;
		.template {
			overflow: hidden;
			.video {
				width: 254rpx;
				height: 338rpx;
			}
			.template-icon {
				width: 162rpx;
				height: 216rpx;
				border-radius: 12rpx;
				overflow: hidden;
				margin: 0 auto;
			}

			.template-name {
				font-size: 28rpx;
				color: #333333;
				font-weight: bold;
				line-height: 140rpx;
			}
		}
	}

	.product-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
	}

	.product-title {
		font-size: 28rpx;
		color: #333333;
	}

	.price {
		font-size: 28rpx;
		color: #333333;
	}

	.coupon-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
	}

	.coupon-text {
		font-size: 28rpx;
		color: #333333;
	}

	.coupon-value {
		font-size: 28rpx;
		color: #7F7F7F;
	}

	.total-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.total-text {
		font-size: 28rpx;
		color: #333333;
	}

	.total-price {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
	}

	.preview-section {
		background-color: #ffffff;
		padding: 15rpx 30rpx 30rpx;

		.active {}
	}

	.preview-images {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.preview-image {
		width: 288rpx;
		height: 378rpx;
		border-radius: 12rpx;
		border: 3px solid #ffffff;
		transition: all 0.5s;
		display: block;
		margin: 0 auto 10rpx;
	}

	.active {
		.preview-image {
			border-color: #FEC207;
		}

		.tixing {
			color: #FEC207;
		}
	}

	.tixing {
		text-align: center;
		color: #999999;
		font-size: 28rpx;
		line-height: 40rpx;
	}

	.preview-tip {
		font-size: 28rpx;
		color: #666666;
		text-align: center;
	}

	.bottom-bar {
		position: fixed;
		bottom: 30rpx;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #ffffff;
		height: 80rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.payment-amount {
		font-size: 28rpx;
		color: #333333;
	}

	.amount {
		color: #D19973;
		font-weight: 600;

	}

	.submit-btn {
		position: absolute;
		right: 30rpx;
		color: #ffffff;
		font-family: PingFang SC;
		font-weight: 500;
		font-style: Heavy;
		font-size: 36rpx;
		leading-trim: NONE;
		line-height: 100rpx;
		letter-spacing: 10%;
		border-radius: 28rpx;
		background: linear-gradient(90deg, #D19973 0%, #EBBD9D 100%);
		width: 422rpx;
		height: 100rpx;
	}
</style>